//app.js


App({
  onShow: function (options) {
    if (wx.canIUse("getUpdateManager")) {
      const updateManager = wx.getUpdateManager();
      updateManager.onCheckForUpdate(function (res) {
         console.log(res.hasUpdate);
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
          updateManager.onUpdateReady(function () {
            wx.showModal({
              title: "更新提示",
              content: "新版本已经准备好，是否重启应用？",
              success(res) {
                if (res.confirm) {
                  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                  updateManager.applyUpdate();
                }
              }
            });
          });
          updateManager.onUpdateFailed(function () {
            // 新的版本下载失败
            wx.showModal({
              title: "已经有新版本了哟~",
              content: "新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~"
            });
          });
        }
      });
    } else {
      wx.showModal({
        title: "提示",
        content:
          "当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。"
      });
    }

  },
  onLaunch: function () {

    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
   
    wx.getSystemInfo({
      success: res=> {
        console.log(res)
        if (res.environment=='wxwork'){
          this.globalData.environment = "wxwork"
        }
        
        this.Login()   
      },
      fail: function(res) {},
      complete: function(res) {},
    })
   
    // 获取用户信息
  /*  wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })*/
  },
  Login(){ 
    

    if (this.globalData.environment === "wxwork") {//企业小程序
      return new Promise((success, rej) =>{
      wx.qy.login({
        success: res => {
          if (res.code) {
            wx.request({
              url: this.globalData.apiurl + 'user/login',
              data: { code: res.code },
              header: {},
              method: 'POST',
              dataType: 'json',
              responseType: 'text',
              success: res=>{
                console.log(res)
                if(res.data.code==="success"){
                  this.globalData.token=res.data.data.access_token
                  if (this.tokenReadyCallback) {
                    this.tokenReadyCallback(res)
                  }
                  success(res)
                }
              },
              fail: res => { rej() },
              complete: function (res) { },
            })
            //发起网络请求

          } else {
           
            console.log('登录失败！' + res.errMsg)
          }
        }
      })
      })
    } else {//普通 小程序
      console.log('小程序登录', '22')
      return new Promise((success, rej) =>{
      wx.login({
          success:res=>{
            console.log('小程序登录',res)
            if (res.code) {
              wx.request({
                url: this.globalData.apiurl + 'user/loginMini',
                data: { code: res.code },
                header: {},
                method: 'POST',
                dataType: 'json',
                responseType: 'text',
                success: res => {
                  console.log(res)
                  if (res.data.code === "success") {
                    this.globalData.token = res.data.data.access_token
                    if (this.tokenReadyCallback) {
                      this.tokenReadyCallback(res)
                    }
                    success(res)
                  }
                },
                fail: res => { rej() },
                complete: function (res) { },
              })
              //发起网络请求
            } else {
              console.log('登录失败！' + res.errMsg)
            }
          }
      
      
      })
      })
    }
  },
  CheckSession(){
    console.log('session',this.globalData.environment)
    if (this.globalData.environment ==="wxwork"){
      if (this.globalData.token) {
      return new Promise((res, rej)=>{
        wx.qy.checkSession({
          success: ()=> {
            console.log('有token的检查')
          
            res(true)
          },
          fail: () => {
            // session_key 已经失效，需要重新执行登录流程
            wx.redirectTo({
              url: '/pages/login/index',
              success: function(res) {},
              fail: function(res) {},
              complete: function(res) {},
            })
          }
        })
      })
      }else{
        return new Promise((res, rej) => {
          this.tokenReadyCallback = success => {
          wx.qy.checkSession({
            success: () => {
              res(true)
            },
            fail: () => {
              // session_key 已经失效，需要重新执行登录流程
              wx.redirectTo({
                url: '/pages/login/index',
                success: function (res) { },
                fail: function (res) { },
                complete: function (res) { },
              })
            }
          })
          } 
        })
      }
    } else{
        //小程序
      if (this.globalData.token) {
        return new Promise((res, rej) => {
          wx.checkSession({
            success: () => {
              console.log('有token的检查')
              res(true)
            },
            fail: () => {
              // session_key 已经失效，需要重新执行登录流程
              wx.redirectTo({
                url: '/pages/login/index',
                success: function (res) { },
                fail: function (res) { },
                complete: function (res) { },
              })
            }
          })
        })
      } else {
        return new Promise((res, rej) => {
          this.tokenReadyCallback = success => {
            wx.checkSession({
              success: () => {
                res(true)
              },
              fail: () => {
                // session_key 已经失效，需要重新执行登录流程
                wx.redirectTo({
                  url: '/pages/login/index',
                  success: function (res) { },
                  fail: function (res) { },
                  complete: function (res) { },
                })
              }
            })
          }
        })
      }

    }
  } , 
  BackUpdate(){
    let pages = getCurrentPages();
    console.log(pages)
    if (pages.length > 1) {
      //上一个页面实例对象
      let prePage = pages[pages.length - 2];
      //关键在这里
      prePage.onLoad()
    } 
  },
  GetUser(){
    
        //判断登录是否已经完成
        if(this.globalData.token){
          return new Promise((res,ret)=>{
            //判断user
            if (this.globalData.userInfo) {
              res(this.globalData.userInfo)
            }else{
              wx.request({
                url: this.globalData.apiurl+'me',
                data: '',
                header: { 'Authorization': 'Bearer ' + this.globalData.token},
                method: 'GET',
                dataType: 'json',
                responseType: 'text',
                success: data=> {
                  this.globalData.userInfo = data.data
                  res(data.data)
                  console.log('有token',data.data)
                 
                },
                fail: function(res) {},
                complete: function(res) {},
              })
            }
          })

        }else{
         return new Promise((res,ret)=>{
           this.tokenReadyCallback = success => {
             if (this.globalData.userInfo) {
               res(this.globalData.userInfo)
             } else {
               wx.request({
                 url: this.globalData.apiurl + 'me',
                 data: '',
                 header: { 'Authorization': 'Bearer ' + success.data.data.access_token },
                 method: 'GET',
                 dataType: 'json',
                 responseType: 'text',
                 success: data=> {
                   this.globalData.userInfo = data.data
                   res(data.data)
                   console.log('么有token', data.data)
                   console.log(data)
                 },
                 fail: function (res) { },
                 complete: function (res) { },
               })
             }
           }
         }) 
       
        }
  },
  globalData: {
    userInfo: null,
  apiurl:'http://127.0.0.1:8000/api/',
    apiAgentUrl:'http://127.0.0.1:8000/agentApi/',
    url:'http://127.0.0.1:8000',
	apiCustomerUrl:'http://127.0.0.1:8000/customerApi/' ,
  /*apiurl:'https://api.sunhouse2002.com/api/',
   apiCustomerUrl:'https://api.sunhouse2002.com/customerApi/',
    apiAgentUrl: 'https://api.sunhouse2002.com/agentApi/',
    url: 'https://api.sunhouse2002.com/',*/

  //  apiurl:'http://127.0.0.1:8000/api/',
   // apiCustomerUrl:'http://127.0.0.1:8000/customerApi/',
   // apiAgentUrl: 'http://127.0.0.1:8000/agentApi/',
   // url: 'http://127.0.0.1:8000/',
    qiniu_url:"https://pic.qalex.com/",
    token:null,
    appId: 'wx1ebb233789d35ea8',
    environment:'',
  }
})